package com.ruoyi.system.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruoyi.common.core.page.PageList;
import com.ruoyi.common.core.page.PageQuery;
import com.ruoyi.common.core.page.PageUtil;
import com.ruoyi.common.utils.bean.BeanUtils;
import com.ruoyi.system.domain.TProdTask;
import com.ruoyi.system.domain.TProdTaskLog;
import com.ruoyi.system.domain.dto.TProdTaskDTO;
import com.ruoyi.system.domain.vo.TProdTaskLogVO;
import com.ruoyi.system.domain.vo.TProdTaskVO;
import com.ruoyi.system.mapper.TProdTaskMapper;
import com.ruoyi.system.service.ITProdRecordService;
import com.ruoyi.system.service.ITProdTaskLogService;
import com.ruoyi.system.service.ITProdTaskService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Objects;

/**
 * @author wux
 * @date 2023/5/26 16:08
 */
@Service
public class TProdTaskServiceImpl extends ServiceImpl<TProdTaskMapper, TProdTask> implements ITProdTaskService {
    @Autowired
    private ITProdRecordService prodRecordService;
    @Autowired
    private ITProdTaskLogService prodTaskLogService;
    @Override
    public List<TProdTaskVO> listByPage(TProdTaskDTO params) {
        PageUtil.startPage(params);
        List<TProdTaskVO> result = this.baseMapper.list(params);
        result.forEach(item -> {
            //查询产品生产批次和已完成产量
            TProdTaskVO temp = prodRecordService.getRecordByProdId(item.getProdId());
            if(Objects.nonNull(temp)){
//                item.setBatchCode(temp.getBatchCode());
                item.setFinishNum(temp.getFinishNum());
            }else {
                item.setFinishNum(0);
            }
            item.setUnFinishNum(item.getPlanNum() - item.getFinishNum());
        });
        return result;
    }

    @Override
    public int sumPlanNum(Long projectId) {
        return this.baseMapper.sumPlanNum(projectId);
    }

    @Override
    @Transactional
    public void saveTaskLog(TProdTaskLog params) {
        //更新生产任务产量
        TProdTask task = baseMapper.selectById(params.getTaskId());
        if(params.getOperationType() == 1){
            task.setPlanNum(task.getPlanNum() + params.getQuantity());
        }else {
            task.setPlanNum(task.getPlanNum() - params.getQuantity());
        }
        baseMapper.updateById(task);
        //保存更新日志
        prodTaskLogService.save(params);
    }

    @Override
    public PageList<TProdTaskLogVO> queryTaskChangeLog(PageQuery page, Long taskId) {
        PageUtil.startPage(page);
        List<TProdTaskLogVO> list = prodTaskLogService.queryTaskChangeLog(taskId);
        return PageUtil.getPageList(list);
    }
}
